clear

%% Estimation Options for Alternative version with sugarcane ethanol as benchmark price:

% Data Location:
opt.DataFolder = '../Data/'; % Use this for Omega
%opt.DataFolder = '..\..\Data\Canasat Detailed\';
opt.ScratchFolder = 'Scratch/';
%opt.ScratchFolder = '/scratch/fas/haile/mc963/';

% Micro, Macro and prices data to be used:
opt.MicroData  = 'G1kmMiRC_V7.mat';
opt.MacroData  = 'AgregateCS_10222014.mat';
opt.PricesData = 'Prices_05212014.mat';

opt.SelSubSample  = 0;  % = 1, Select Subsample of Tracts
                        % = 0, Work with full data
opt.SubSampleFrac = .05; % Fraction of sample selected randomly

opt.Buffer40km = 0; % = 1, Work only with fields that fall in the 40km buffer zone
                    % = 0, Work with all fields
opt.SPonly = 0;     % = 1, Use only state of SP
                    % = 0, Use all region CS
                    
opt.Years = [2005:2012]; % Select years to use for estimation. All years are used
                         % to build field ages.
                         
opt.NotPantanal = 1; % = 1, Not use Pantanal (cannot plant sugarcane there)  

opt.NotUcsIndian = 1; % =1, eliminate all fields in UCs and Indian reserves

% Use fakedata:
opt.fakedata = 0; % = 1, use fake data 
                  % = 0, use real data 
                  % Parameters for generating fakedata are stored in generate_fakedataM6.m
% Maximum age:
opt.MaxAge = 9;

% Age Truncation:
opt.TrunkAge = 0; % = 1, truncation
                  % = 0, no truncation                  
opt.TrunkAgeLevel = 10; % Age level for truncation


opt.SaveResultsAs = 'Results/ethanol';
opt.Restart = 1; % = 1 save partial results of probabilities and theta and restart

%% Distance to sugarcane state options:
opt.SRDthresholds = [0 3 15 40];
%opt.SRDthresholds = [0 10 40];

%% Exogenous Fixed State variables options:

% Pastures and cropland from MapBiomas

% Distance variable used:
opt.TransCostVar   = 'SugarTransportCostR';
opt.TransCostVarRS = 1/2204; % If transport cost in reais per ton and price is in reais per lb. Make the two compatible.
% Sugarcane potential yield used:
opt.PotenYield   = 'gaez_aecol_suc';
opt.PotenYieldRS = 1/1000;
% Cost related variables factors:
opt.CostVar = {'Altitude' 'prec_growth'};

% Number of classes for each exogenous fixed state (split in quantiles):
opt.NumFixedStates = 4;
% Use normalized regressors (not included yield and transportation cost):
opt.UseNormalizedReg = 1; % = 1 Use normalized regressors,
                          % = 0 Use regressors at actual level

%% Exogenous Time State variables options:

opt.WhichOutside = 2; % Deprecated option. Only 2 is admissible.

%% Options for full outside option model:
% Folder where codes and results for the outside model are stored:
opt.OutsideOptionModelFolder   = '..\Outside Option Model\';
% File where outside model are saved:
opt.OutsideOptionResult        = 'RCOM4_AltSqSoilRainMeso.mat';  

opt.EstimateOutsideOption = 0; % = 1 Re-estimate Outside option model
                               % = 0 Not re-estimate model. Load
                               % opt.OutsideOptionResult instead
                               
% Quantiles to be used in outisde option state classification:                              
%opt.QuantilesOutOption = [0 .4 .6 .7 .8 .85 .9 .925 .95 .975 1];
%opt.QuantilesOutOption = [0 .5 .8 .9 .95 .975 1];
opt.NumPartialStatesFull = 5; % Number of quantiles for state classifications for partial derivative

%% Options for simple outside option model (2) or Old formulation (3):
opt.RegionVariable   = 'meso_reg'; % This can be 'micro_reg', 'meso_reg' or 'uf'
opt.NumPartialStates = 3; % Number of quantiles for state classifications for yield x share  


% Sugar price used:
opt.SugarPrice    = 'p_hydethanolbr_lag';

% Outside option payoff prices:
% Careful to make this compatible with prices used in the outside model estimation.
opt.CornPrice     = 'c1brl_lag'; 
opt.SoyPrice      = 's1brl_lag';

% Options for discretizing the price process
opt.pproc.Ns        = 4; % Number of states for the price process
opt.pproc.bandwidth = 2; % Number of standards deviations for the Tauchen discretization


%% NPL Options

% Discounting:
opt.rho      = .9;
opt.NPLtol   = 10^-5; % tol for NPL iteration
opt.max_iter = 15; % Max k-steps


%% Initial guess:

% Payoffs:
opt.ini.gamma  = .76;  % Yield decay.
opt.ini.thetaR = .1;    % Region specific coefficient in sugarcane payoff

% Fixed implementation cost:
opt.ini.PsiE   = 2;
% Fixed replanting cost:
opt.ini.PsiR   = 5;
% Fixed sugarcane abandoning cost: 
opt.ini.PsiA   = 7;
% Initial yield (same for all regions in this version of the model):
opt.ini.kappa  = .2;
% Initial value for fixed exogenous cost coef. :
opt.ini.beta   = .1;


if opt.fakedata == 1 % Use fake data;
    [DS,Action,AgeState,AgregateCS] = generate_fakedataM6(opt);
else %  use real data
    [FID_Grid,Action,Age,AgeState,States,pproc] = prepdataM10(opt);
end

opt.IsBoot = 0;
[theta_est,covar,p_unob_het] = AM_Estimation2(FID_Grid,States,AgeState,Action,pproc,opt);

theta_std = sqrt(diag(covar));
disp(' Results - coef and std err ')
[theta_est theta_std]


clear DS States AgeState Action
save([opt.SaveResultsAs '.mat']);


